package com.jilefojing.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.web.response.AudioData;
import com.jilefojing.beans.data.web.response.DCategoryData;
import com.jilefojing.beans.enums.ItemTypeEnumForSource;
import com.jilefojing.beans.enums.ProgressStatusForSource;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.RCategorySource;
import com.jilefojing.beans.pojos.Statistics;
import com.jilefojing.beans.pojos.enhanced.EnhancedComment;
import com.jilefojing.beans.pojos.enhanced.EnhancedDCategory;
import com.jilefojing.beans.pojos.enhanced.EnhancedEAudio;
import com.jilefojing.beans.pojos.enhanced.EnhancedStatistics;
import com.jilefojing.beans.pojos.enhanced.EnhancedTag;
import com.jilefojing.beans.pojos.enhanced.base.BaseEnhanced;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.ICommentService;
import com.jilefojing.service.IDCategoryService;
import com.jilefojing.service.IEAudioService;
import com.jilefojing.service.ISourceService;
import com.jilefojing.service.IStatisticsService;
import com.jilefojing.service.ITagService;
import com.jilefojing.util.Detect;
import com.jilefojing.web.base.BaseWeb;
import com.jilefojing.web.convent.CommonConvent;

@Controller
@RequestMapping("audio")
public class AudioWeb extends BaseWeb {
	@Autowired
	private IEAudioService eAudioService;
	@Autowired
	private IDCategoryService dCategoryService;
	@Autowired
	private ICommentService commentService;
	@Autowired
	private ISourceService sourceService;
	@Autowired
	private IStatisticsService statisticsService;
	@Autowired
	private ITagService tagService;

	@RequestMapping("list-tag-{tagId}/part.html")
	public String getTagAudioListPartPage(@PathVariable("tagId") long tagId, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}

		EnhancedTag enhancedTag = (EnhancedTag) tagService.getEnhanced(tagId, userContext);
		if (enhancedTag == null) {
			throw new UserContextException(ResponseEnum.TAG_NOT_EXIST);
		}
		request.setAttribute("tag", CommonConvent.convent2TagData(enhancedTag));

		Pagination<EnhancedEAudio> pagination = new Pagination<EnhancedEAudio>(page, 12, true);

		pagination = eAudioService.getPaginationByTagIdForActive(tagId, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedCommons(pagination.getItems(), userContext));
			pagination.setItems(eAudioService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEAudio(pagination.getItems());

			if (userContext != null) {
				pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}

			request.setAttribute("pagination", pagination);
			request.setAttribute("audios", CommonConvent.convent2EAudioDatas(pagination.getItems()));
		}

		return "web/audio/tag_audio_list_part";
	}

	/**
	 * 获取视频列表 -- 标签获取
	 * 
	 * @param request
	 * @return
	 * @throws UserContextException
	 */
	@RequestMapping("list-tag-{tagId}.html")
	public String toTagAudioListPage(@PathVariable("tagId") long tagId, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}

		EnhancedTag enhancedTag = (EnhancedTag) tagService.getEnhanced(tagId, userContext);
		if (enhancedTag == null) {
			throw new UserContextException(ResponseEnum.TAG_NOT_EXIST);
		}
		request.setAttribute("tag", CommonConvent.convent2TagData(enhancedTag));

		Pagination<EnhancedEAudio> pagination = new Pagination<EnhancedEAudio>(page, 12, true);

		pagination = eAudioService.getPaginationByTagIdForActive(tagId, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedCommons(pagination.getItems(), userContext));
			pagination.setItems(eAudioService.appendEnhancedChildren(pagination.getItems(), userContext));
			this.resetEnhancedStatistics2NotEntityEnhancedEAudio(pagination.getItems());

			if (userContext != null) {
				pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}

			request.setAttribute("pagination", pagination);
			request.setAttribute("audios", CommonConvent.convent2EAudioDatas(pagination.getItems()));
		}

		Pagination<EnhancedTag> hotEnhancedTagPagination = new Pagination<EnhancedTag>(1, 10, false);
		// 获取热门标签
		hotEnhancedTagPagination = tagService.getPaginationByItemTypesForHot(Arrays.asList(new ItemTypeEnumForSource[] { ItemTypeEnumForSource.AUDIO }), hotEnhancedTagPagination, userContext);
		if (Detect.notEmpty(hotEnhancedTagPagination.getItems())) {
			request.setAttribute("hotTags", CommonConvent.convent2TagDatas(hotEnhancedTagPagination.getItems()));
		}

		return "web/audio/tag_audio_list";
	}

	/**
	 * 获取音频播放页面
	 * 
	 * @param id
	 * @param request
	 * @return
	 * @throws UserContextException
	 */
	@RequestMapping("{id}.html")
	public String toAudioPage(@PathVariable("id") long id, HttpServletRequest request) throws UserContextException {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		EnhancedEAudio enhancedEAudio = eAudioService.getEnhancedForActive(id, userContext);
		if (userContext != null) {
			enhancedEAudio = (EnhancedEAudio) eAudioService.appendEnhancedExtralsForUser(enhancedEAudio, userContext);
		}
		request.setAttribute("audio", CommonConvent.convent2EAudioData(enhancedEAudio));

		EnhancedEAudio enhancedAudioSource = null;
		if (!enhancedEAudio.isEntity()) {// 是音频集合
			enhancedEAudio = eAudioService.appendEnhancedChildren(enhancedEAudio, userContext);
			enhancedAudioSource = enhancedEAudio;
		} else {// 是单个音频体
			if (enhancedEAudio.getEnhancedParent() != null && enhancedEAudio.getEnhancedParent().getId() > 0) {// 有所属关系时
				EnhancedEAudio enhancedParentEAudio = (EnhancedEAudio) eAudioService.getEnhanced(enhancedEAudio.getEnhancedParent().getId(), userContext);
				enhancedParentEAudio = eAudioService.appendEnhancedChildren(enhancedParentEAudio, userContext);
				enhancedAudioSource = enhancedParentEAudio;
			} else {// 无所属关系时
				enhancedAudioSource = enhancedEAudio;
			}
		}
		if (userContext != null) {
			enhancedAudioSource = (EnhancedEAudio) eAudioService.appendEnhancedExtralsForUser(enhancedAudioSource, userContext);
		}

		request.setAttribute("audioSource", CommonConvent.convent2EAudioData(enhancedAudioSource));

		Pagination<EnhancedComment> enhancedHotCommentPagination = new Pagination<EnhancedComment>(1, 3, true);
		enhancedHotCommentPagination = commentService.getPaginationForHot(ItemTypeEnumForSource.AUDIO, enhancedEAudio.getId(), enhancedHotCommentPagination, userContext);

		Pagination<EnhancedComment> enhancedCommentPagination = new Pagination<EnhancedComment>(1, 10, true);
		enhancedCommentPagination = commentService.getPaginationForActive(ItemTypeEnumForSource.AUDIO, enhancedEAudio.getId(), enhancedCommentPagination, userContext);
		request.setAttribute("enhancedCommentPagination", enhancedCommentPagination);

		List<EnhancedComment> allEnhancedComments = new ArrayList<EnhancedComment>();// 所有评论
		if (Detect.notEmpty(enhancedCommentPagination.getItems())) {
			allEnhancedComments.addAll(enhancedCommentPagination.getItems());
		}
		if (Detect.notEmpty(enhancedHotCommentPagination.getItems())) {
			allEnhancedComments.addAll(enhancedHotCommentPagination.getItems());
		}
		if (Detect.notEmpty(allEnhancedComments) && userContext != null) {
			allEnhancedComments = commentService.appendEnhancedAttitude2EnhancedCommentsForUser(allEnhancedComments, userContext);
		}

		if (Detect.notEmpty(enhancedCommentPagination.getItems())) {
			request.setAttribute("comments", CommonConvent.convent2CommentDatas(enhancedCommentPagination.getItems()));
		}

		if (Detect.notEmpty(enhancedHotCommentPagination.getItems())) {
			request.setAttribute("hotComments", CommonConvent.convent2CommentDatas(enhancedHotCommentPagination.getItems()));
		}

		Pagination<? extends BaseEnhanced> relationPagination = new Pagination<EnhancedEAudio>(1, 8, false);

		relationPagination = sourceService.getPaginationForCorrelation(ItemTypeEnumForSource.AUDIO, enhancedEAudio.getId(), Arrays.asList(new ItemTypeEnumForSource[] { ItemTypeEnumForSource.AUDIO }),
				relationPagination, userContext);

		if (Detect.notEmpty(relationPagination.getItems())) {
			relationPagination.setItems((List) eAudioService.appendEnhancedChildren((List<EnhancedEAudio>) relationPagination.getItems(), userContext));
			if (userContext != null) {
				relationPagination.setItems((List) eAudioService.appendEnhancedExtralsForUser(relationPagination.getItems(), userContext));
			}
			this.resetEnhancedStatistics2NotEntityEnhancedEAudio((List<EnhancedEAudio>) relationPagination.getItems());
			request.setAttribute("relationAudios", CommonConvent.convent2EAudioDatas((List<EnhancedEAudio>) relationPagination.getItems()));
		}

		statisticsService.updateCount(ItemTypeEnumForSource.AUDIO, enhancedEAudio.getId(), Statistics.COLUMN_COUNT_WATCH, true, 1, userContext);// 更新观看总数

		return "web/audio/audio";
	}

	/**
	 * 分页获取的音频列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("list-part.html")
	public String getAudioListPart(HttpServletRequest request) {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		List<Long> categoryIds = this.getIds(request, "cat");

		short sort = 0;
		String sortStr = request.getParameter("sort");
		if (Detect.notEmpty(sortStr)) {
			sort = Short.valueOf(sortStr);
		}
		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}
		short progress = 0;
		String progressStr = request.getParameter("progress");
		if (Detect.notEmpty(progressStr)) {
			progress = Short.parseShort(progressStr);
		}

		// cat=1~2~5-31~3~8 --->两种选择交集
		Pagination<EnhancedEAudio> pagination = new Pagination<EnhancedEAudio>(page, 20, true);
		if (sort == 1) {// 热门
			pagination.addOrder(new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC));
		} else if (sort == 2) {// 最近更新
			pagination.addOrder(new Order(RCategorySource.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		}
		List<ProgressStatusForSource> progressStatuses = null;
		if (ProgressStatusForSource.getProgressStatusEnumByCode(progress) != null) {
			progressStatuses = Arrays.asList(new ProgressStatusForSource[] { ProgressStatusForSource.getProgressStatusEnumByCode(progress) });
		}

		pagination = eAudioService.getPaginationByCategoryIdsForActive(categoryIds, progressStatuses, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eAudioService.appendEnhancedChildren(pagination.getItems(), userContext));
			if (userContext != null) {
				pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}
			this.resetEnhancedStatistics2NotEntityEnhancedEAudio(pagination.getItems());
			List<AudioData> audioDatas = CommonConvent.convent2EAudioDatas(pagination.getItems());
			request.setAttribute("audios", audioDatas);
			request.setAttribute("pagination", pagination);
		}

		return "web/audio/audio_list_part";
	}

	private List<Long> getIds(HttpServletRequest request, String key) {
		String valsStr = request.getParameter(key);
		if (Detect.notEmpty(valsStr)) {
			String[] valStrs = valsStr.split("~");
			List<Long> valIds = new ArrayList<Long>();
			for (String valStr : valStrs) {
				long valLong = Long.valueOf(valStr);
				if (valLong > 0) {
					valIds.add(valLong);
				}
			}
			return valIds;
		}
		return null;
	}

	@RequestMapping("list.html")
	public String toAudioListPage(HttpServletRequest request) {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (Exception ex) {
			// 可忽略
		}

		Pagination<EnhancedEAudio> pagination = new Pagination<EnhancedEAudio>(1, 20, true);
		pagination.addOrder(new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC));
		pagination = eAudioService.getPaginationByCategoryIdsForActive(null, null, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eAudioService.appendEnhancedChildren(pagination.getItems(), userContext));
			if (userContext != null) {
				pagination.setItems((List<EnhancedEAudio>) eAudioService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}
			this.resetEnhancedStatistics2NotEntityEnhancedEAudio(pagination.getItems());

			List<AudioData> audioDatas = CommonConvent.convent2EAudioDatas(pagination.getItems());
			request.setAttribute("audios", audioDatas);
			request.setAttribute("pagination", pagination);
		}

		List<EnhancedDCategory> enhancedDCategories = eAudioService.getEnhancedDCategories(userContext);
		if (Detect.notEmpty(enhancedDCategories)) {
			List<DCategoryData> dCategoryDatas = CommonConvent.convent2DCategoryDatas(enhancedDCategories);
			request.setAttribute("dCategorys", dCategoryDatas);
		}
		return "web/audio/audio_list";
	}

	private void resetEnhancedStatistics2NotEntityEnhancedEAudio(List<EnhancedEAudio> enhancedEAudios) {
		for (EnhancedEAudio _EnhancedEAudio : enhancedEAudios) {
			if (!_EnhancedEAudio.isEntity() && Detect.notEmpty(_EnhancedEAudio.getEnhancedChildren())) {
				EnhancedStatistics enhancedStatistics = new EnhancedStatistics();
				enhancedStatistics.setItemType(ItemTypeEnumForSource.AUDIO);
				for (EnhancedEAudio _childEnhancedEAudio : _EnhancedEAudio.getEnhancedChildren()) {
					if (_childEnhancedEAudio.getEnhancedStatistics() != null) {
						enhancedStatistics.setCountComment(enhancedStatistics.getCountComment() + _childEnhancedEAudio.getEnhancedStatistics().getCountComment());
						enhancedStatistics.setCountWatch(enhancedStatistics.getCountWatch() + _childEnhancedEAudio.getEnhancedStatistics().getCountWatch());
						enhancedStatistics.setCountPraise(enhancedStatistics.getCountPraise() + _childEnhancedEAudio.getEnhancedStatistics().getCountPraise());
						enhancedStatistics.setCountFavorite(enhancedStatistics.getCountFavorite() + _childEnhancedEAudio.getEnhancedStatistics().getCountFavorite());
					}
				}
				_EnhancedEAudio.setEnhancedStatistics(enhancedStatistics);
			}
		}
	}

}
